package com.db.httpserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public final class WorkerThread implements Runnable {

    private final Socket socket;
    
    private WorkerThread(Socket socket) {
        this.socket = socket;
    }

    public static void startPool(int suggestedPort) throws IOException {
        Parameter.setPort(suggestedPort);
        Parameter.print();
        int port = Parameter.getPort();
        int workers = Parameter.getWorkers();
        int timeout = Parameter.getTimeout(); 
        
        // create pool of worker threads
        final ExecutorService pool = Executors.newFixedThreadPool(workers);
        // create server socket
        final ServerSocket serverSocket = new ServerSocket(port);
        // accept connections
        while (true) {
            Socket socket = serverSocket.accept();
            socket.setSoTimeout(timeout);
            pool.execute(new WorkerThread(socket));
        }
    }

    public void run() {
    
        AbstractHttpWorker worker = new Worker();
        try {
            worker.handleRequest(socket);
        } catch (IOException e) {
            e.printStackTrace();
            try {
                socket.close();
            } catch (IOException exc) {
                // don't care
            }
        }
         
    }
}